package com.ming.common.beetl.util;

import com.ming.common.Options;
import com.ming.common.beetl.entity.BaseEntity;
import com.ming.common.beetl.vo.IvyPageResult;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.page.PageResult;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class SQLManagerUtil {

    private volatile static SQLManagerUtil instance;
    private SQLManagerUtil(){ }
    public  static SQLManagerUtil NEW() {
        if (instance == null){
            synchronized (SQLManagerUtil.class){
                if (instance == null){
                    instance = new SQLManagerUtil();
                }
            }
        }
        return instance;
    }

    private SQLManager sqlManager;

    private String tableName;

    private String primaryKey;

    public SQLManagerUtil sqlManager(SQLManager sqlManager){
        this.sqlManager = sqlManager;
        return this;
    }

    public SQLManagerUtil tableName(String tableName){
        this.tableName = tableName;
        return this;
    }

    public SQLManagerUtil primaryKey(String primaryKey){
        this.primaryKey = primaryKey;
        return this;
    }

    public List<? extends BaseEntity> selectAll(){
        return QueryUtil.selectAll(sqlManager,tableName);
    }

    public PageResult<? extends BaseEntity> selectPage(Options options){
        return QueryUtil.selectPage(sqlManager,tableName,options);
    }

    public IvyPageResult selectIvyPage(Options options){
        return QueryUtil.selectIvyPage(sqlManager,tableName,options);
    }

    public Map<String, ? extends BaseEntity> selectAllToStrMap(Function<? super BaseEntity, ? extends String> keyMapper, Function<? super BaseEntity, ? extends BaseEntity> valueMapper) {
        List<? extends BaseEntity> dataSourceList = selectAll();
        return dataSourceList.stream().collect(Collectors.toMap(keyMapper, valueMapper));
    }

    public Map<Long, ? extends BaseEntity> selectAllToLongMap(Function<? super BaseEntity, ? extends Long> keyMapper, Function<? super BaseEntity, ? extends BaseEntity> valueMapper) {
        List<? extends BaseEntity> dataSourceList = selectAll();
        return dataSourceList.stream().collect(Collectors.toMap(keyMapper, valueMapper));
    }

    public int insert(Map<String,Object> data) {
        return QueryUtil.insertSelective(sqlManager,tableName,data);
    }

    public int updateById(Map<String,Object> data) {
        return QueryUtil.updateSelectiveById(sqlManager,tableName,data,primaryKey);
    }

    public int deleteById(Map<String,Object> data) {
        return QueryUtil.deleteById(sqlManager,tableName,data,primaryKey);
    }
}
